package org.quarenden.demo.controller;

import org.quarenden.demo.aggregate.AggregationService;
import org.quarenden.demo.pojo.MicroService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import rx.Observable;
import rx.Observer;

import java.util.HashMap;

@RestController
public class AggregationController {
    public static final Logger logger = LoggerFactory.getLogger(AggregationController.class);

    @Autowired
    private AggregationService aggregationService;

    @GetMapping("/all/{id}")
    public DeferredResult<HashMap<String, MicroService>> aggregate(@PathVariable String id) {
        Observable<HashMap<String, MicroService>> result = this.aggregateObservableQueryMicroService(id);
        return this.toDeferredResultQueryMicroService(result);
    }

    public Observable<HashMap<String, MicroService>> aggregateObservableQueryMicroService(String id) {
        // 合并两个或者多个Observables发射出的数据项，根据指定的函数变换它们
        return Observable.zip(
                this.aggregationService.getMicroService1(id),
                this.aggregationService.getMicroService2(id),
                (microService1, microService2) -> {
                    HashMap<String, MicroService> map = new HashMap<>();
                    map.put("microService1", microService1);
                    map.put("microService2", microService2);
                    return map;
                }
        );
    }

    public DeferredResult<HashMap<String,MicroService>> toDeferredResultQueryMicroService(Observable<HashMap<String, MicroService>> details){
        DeferredResult<HashMap<String,MicroService>> result = new DeferredResult<HashMap<String,MicroService>>();

        details.subscribe(new Observer<HashMap<String, MicroService>>() {
            @Override
            public void onCompleted() {
                logger.info("complete....");
            }

            @Override
            public void onError(Throwable throwable) {
                logger.error("error:",throwable);

            }

            @Override
            public void onNext(HashMap<String, MicroService> stringMicroServiceHashMap) {
                result.setResult(stringMicroServiceHashMap);
            }
        });

        return result;
    }
}
